<?php

declare(strict_types=1);

namespace app\model\admin;

use app\eslib\EsUtils;
use app\model\AuthAdminsModel;
use think\helper\Str;

/**
 * @mixin \think\Model
 */
class LoginModel
{
    public static function login($formData, $ip)
    {
        // 表单校验
        $validator =  \think\facade\Validate::rule([
            'user_name|用户名' => 'require|min:3|max:150',
            'password|密码' => 'require|min:3|max:150',
        ]);
        if (!$validator->check($formData)) {
            return EsUtils::stdMessage(false, $validator->getError());
        }
        // 表单数据处理
        extract($formData);
        try {
            $model = AuthAdminsModel::where(['user_name' => $user_name])->find();
            if (!$model) {
                return EsUtils::stdMessage(false, '用户不存在');
            }
            // if ($appFlag != $model->app_flag) {
            //     return EsUtils::stdMessage(false, '用户应用域错误');
            // }
            if ($model->status != 1) {
                return EsUtils::stdMessage(false, '用户状态错误');
            }
            if (EsUtils::hashPassword($password, $model->salt) != $model->password) {
                return EsUtils::stdMessage(false, '密码错误');
            }
            // 记录登录时间和IP
            $model->login_time = date('Y-m-d H:i:s');
            $model->login_ip = $ip;
            $model->login_count += 1;
            $model->save();
            $id = $model->id;
            unset($model);
            return EsUtils::stdMessage(true, '', LoginState::getJwt($id));
        } catch (\Exception $ex) {
            // 解决 PHP 错误: Malformed UTF-8 characters, possibly incorrectly encoded.
            return EsUtils::stdMessage(false, mb_convert_encoding($ex->getMessage(), 'UTF-8', 'UTF-8,GBK,GB2312,BIG5'));
        }
    }

    public static function regist($formData, $ip)
    {
        // 表单校验
        $validator =  \think\facade\Validate::rule([
            'user_name|用户名' => 'require|min:3|max:150',
            'password|密码' => 'require|min:3|max:150',
            'repassword|确认密码' => 'require|same:password',
        ]);
        if (!$validator->check($formData)) {
            return EsUtils::stdMessage(false, $validator->getError());
        }
        // 表单数据处理
        $formData['salt'] = Str::random(8);
        $formData['password'] = EsUtils::hashPassword($formData['password'], $formData['salt']);
        $formData['login_time'] = date('Y-m-d H:i:s');
        $formData['login_ip'] = $ip;
        $formData['register_ip'] = $ip;
        $formData['status'] = 2;
        try {
            if (AuthAdminsModel::where(['user_name' => $formData['user_name']])->count()) {
                return EsUtils::stdMessage(false, '用户名已被注册');
            }
            $model = AuthAdminsModel::create($formData);
            return EsUtils::stdMessage(true, '', LoginState::getJwt($model->id));
        } catch (\Exception $ex) {
            return EsUtils::stdMessage(false, $ex->getMessage());
        }
    }
}
